package com.witte.configure;

import java.io.File;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.unit.DataSize;
import com.witte.listener.MySessionListener;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements WebMvcConfigurer{
	//最大上传大小
	@Bean
	public MultipartConfigElement multipartConfigElement() {
	    MultipartConfigFactory factory = new MultipartConfigFactory();
	    factory.setMaxFileSize(DataSize.ofMegabytes(180));
	    factory.setMaxRequestSize(DataSize.ofMegabytes(180));
	    return factory.createMultipartConfig();
	}
	
	//跨域
	@Bean		
	  public FilterRegistrationBean corsFilter() {
	    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	    source.registerCorsConfiguration("/**", buildConfig());
	    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
	    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
	    return bean;
	  }
	
	//跨域
	 private CorsConfiguration buildConfig() {
		    CorsConfiguration corsConfiguration = new CorsConfiguration();
		    corsConfiguration.addAllowedOrigin("*");
		    corsConfiguration.addAllowedHeader("*");
		    corsConfiguration.addAllowedMethod("*");
		    corsConfiguration.setAllowCredentials(true);
		    return corsConfiguration;
	 }
	
	//在线人数统计
	@Bean
    public ServletListenerRegistrationBean getListener() {
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new MySessionListener());
        return servletListenerRegistrationBean;
    }

	//设置静态文件资源
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String dir=System.getProperty("user.dir");
		registry.addResourceHandler("/image/**").addResourceLocations("file:"+dir+File.separator+"image"+File.separator);
		super.addResourceHandlers(registry);
	}
}
